<template>

  <view class="calculator-container">
    <!-- 计算表单区域 -->
    <view class="calculator-form">
      <view class="form-row">
        <text class="label">价格</text>
        <input 
          type="digit" 
          v-model="form.price" 
          placeholder="元"
          @input="handleInput($event, 'price')"
        />
		<text class="unit">元</text>
      </view>
      <view class="form-row">
        <text class="label">成本</text>
        <input 
          type="digit" 
          v-model="form.cost" 
          placeholder="元"
          @input="handleInput($event, 'cost')"
        />
		<text class="unit">元</text>
      </view>
      <view class="form-row">
        <text class="label">退货率</text>
        <input 
          type="digit" 
          v-model="form.returnRate" 
          placeholder="%"
          @input="handleInput($event, 'returnRate')"
        />
		<text class="unit">%</text>
      </view>
      <view class="form-row">
        <text class="label">平台费率</text>
        <input 
          type="digit" 
          v-model="form.platformFee" 
          placeholder="%"
          @input="handleInput($event, 'platformFee')"
        />
		<text class="unit">%</text>
      </view>
    </view>

    <!-- 按钮区域 -->
    <view class="button-group">
      <button class="btn reset" @tap="handleReset">重置</button>
      <button class="btn calculate" @tap="handleCalculate">计算</button>
    </view>

    <!-- 计算结果区域 -->
    <view class="result-area" v-if="showResult">
      <view class="result-title">计算结果</view>
      
      <view class="result-row">
        <view class="result-item">
          <text>预估利润：</text>
          <text class="value">{{result.estimatedProfit}}元</text>
        </view>
        <view class="result-item">
          <text>结算利润：</text>
          <text class="value">{{result.actualProfit}}元</text>
        </view>
      </view>

      <view class="result-row">
        <view class="result-item">
          <text>毛利润率：</text>
          <text class="value">{{result.grossProfitRate}}%</text>
        </view>
        <view class="result-item">
          <text>纯利润率：</text>
          <text class="value">{{result.netProfitRate}}%</text>
        </view>
      </view>

      <view class="result-row">
        <view class="result-item">
          <text>预估ROI：</text>
          <text class="value">{{result.estimatedROI}}</text>
        </view>
        <view class="result-item">
          <text>保本ROI：</text>
          <text class="value">{{result.breakEvenROI}}</text>
        </view>
      </view>

      <view class="price-suggestions">
        <view class="suggestion-title">随心推/千川投流出价</view>
        <view class="suggestions-grid">
          <view class="suggestion-column">
            <view v-for="(item, index) in result.priceGuide.slice(0,4)" :key="index">
              <text>{{item.multiple}}倍出价：</text>
              <text class="price">{{item.price}}</text>
            </view>
            <view>
              <text>ROI出价：</text>
              <text class="price">{{result.roiPriceRange.range1}}</text>
            </view>
          </view>
          <view class="suggestion-column">
            <view v-for="(item, index) in result.priceGuide.slice(4)" :key="index">
              <text>{{item.multiple}}倍出价：</text>
              <text class="price">{{item.price}}</text>
            </view>
            <view>
              <text>ROI出价：</text>
              <text class="price">{{result.roiPriceRange.range2}}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="calculation-time">
        计算时间：{{result.calculationTime}}
      </view>
      <view class="calculation-note">
        PS：投放出价按纯佣金计算而得，1.0倍即是保本出价
      </view>

      <button class="copy-result" @tap="copyResult">复制结果</button>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MerchantCalculator',
  data() {
    return {
      form: {
        price: '',
        cost: '',
        returnRate: '5',
        platformFee: '5'
      },
      showResult: false,
      result: {
        estimatedProfit: '0.00',
        actualProfit: '0.00',
        grossProfitRate: '0.00',
        netProfitRate: '0.00',
        estimatedROI: '0.00',
        breakEvenROI: '0.00',
        priceGuide: [],
        roiPriceRange: {
          range1: '0.00~0.00',
          range2: '0.00~0.00'
        },
        calculationTime: ''
      }
    }
  },
  methods: {
    handleReset() {
      this.form = {
        price: '',
        cost: '',
        returnRate: '5',
        platformFee: '5'
      }
      this.showResult = false
    },

    handleCalculate() {
      if (!this.validateInput()) {
        return
      }

      const price = parseFloat(this.form.price)
      const cost = parseFloat(this.form.cost)
      const returnRate = parseFloat(this.form.returnRate) / 100
      const platformFee = parseFloat(this.form.platformFee) / 100

      // 计算逻辑
      const estimatedProfit = price - cost  // 预估利润
      const actualProfit = estimatedProfit - (price * platformFee)  // 结算利润
      const grossProfitRate = (1 - (cost / price)) * 100  // 毛利润率
      const netProfitRate = grossProfitRate - (this.form.platformFee)  // 纯利润率

      // 计算ROI
      const estimatedROI = grossProfitRate > 0 ? 1 / (grossProfitRate * 0.01) : 0  // 预估ROI
      const breakEvenROI = grossProfitRate > 0 ? 1 / ((grossProfitRate * 0.01) * (1 - returnRate - platformFee)) : 0  // 保本ROI

      // 生成价格指导
      const priceGuide = this.generatePriceGuide(actualProfit)

      // 计算ROI出价范围
      const roiPriceRange = {
        range1: `${this.formatNumber(breakEvenROI * 1.1)}~${this.formatNumber(breakEvenROI * 1.2)}`,
        range2: `${this.formatNumber(estimatedROI * 0.9)}~${this.formatNumber(estimatedROI * 1.2)}`
      }

      this.result = {
        estimatedProfit: this.formatNumber(estimatedProfit),
        actualProfit: this.formatNumber(actualProfit),
        grossProfitRate: this.formatNumber(grossProfitRate),
        netProfitRate: this.formatNumber(netProfitRate),
        estimatedROI: this.formatNumber(estimatedROI),
        breakEvenROI: this.formatNumber(breakEvenROI),
        priceGuide,
        roiPriceRange,
        calculationTime: this.getCurrentTime()
      }

      this.showResult = true
    },

    validateInput() {
      const isValidNumber = (value) => {
        const num = parseFloat(value)
        return !isNaN(num) && num >= 0 && value.trim() !== ''
      }

      if (!isValidNumber(this.form.price)) {
        uni.showToast({ title: '请输入有效的价格', icon: 'none' })
        return false
      }
      if (!isValidNumber(this.form.cost)) {
        uni.showToast({ title: '请输入有效的成本', icon: 'none' })
        return false
      }
      if (!isValidNumber(this.form.returnRate)) {
        uni.showToast({ title: '请输入有效的退货率', icon: 'none' })
        return false
      }
      if (!isValidNumber(this.form.platformFee)) {
        uni.showToast({ title: '请输入有效的平台费', icon: 'none' })
        return false
      }

      const price = parseFloat(this.form.price)
      const cost = parseFloat(this.form.cost)
      if (price < cost) {
        uni.showToast({ title: '价格不能低于成本', icon: 'none' })
        return false
      }

      const totalRate = parseFloat(this.form.returnRate) + parseFloat(this.form.platformFee)
      if (totalRate >= 100) {
        uni.showToast({ title: '费率总和不能超过100%', icon: 'none' })
        return false
      }

      return true
    },

    generatePriceGuide(baseProfit) {
      const multiples = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5]
      return multiples.map(multiple => ({
        multiple: multiple.toFixed(1),
        price: this.formatNumber(baseProfit * multiple)
      }))
    },

    formatNumber(num) {
      return Number(num).toFixed(2)
    },

    getCurrentTime() {
      return new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
    },

    copyResult() {
      const resultText = `计算结果
预估利润: ${this.result.estimatedProfit}元
结算利润: ${this.result.actualProfit}元
毛利润率: ${this.result.grossProfitRate}%
纯利润率: ${this.result.netProfitRate}%
预估ROI: ${this.result.estimatedROI}
保本ROI: ${this.result.breakEvenROI}

随心推/千川投流出价:
${this.result.priceGuide.map(item => `${item.multiple}倍出价: ${item.price}`).join('\n')}

ROI出价: ${this.result.roiPriceRange.range1}
ROI出价: ${this.result.roiPriceRange.range2}

计算时间: ${this.result.calculationTime}
PS: 投放出价按纯佣金计算而得，1.0倍即是保本出价。\n\n\n` +
`本结果由"电商计算器"小程序生成，微信搜索"电商计算器"即可免费使用。`

      uni.setClipboardData({
        data: resultText,
        success: () => {
          uni.showToast({ title: '复制成功', icon: 'success' })
        }
      })
    },

    handleInput(event, field) {
      let value = event.detail.value
      
      // 移除非数字和小数点
      value = value.replace(/[^\d.]/g, '')
      
      // 确保只有一个小数点
      const parts = value.split('.')
      if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('')
      }
      
      // 限制小数位数为2位
      if (parts.length === 2 && parts[1].length > 2) {
        value = parts[0] + '.' + parts[1].slice(0, 2)
      }
      
      this.form[field] = value
    }
  }
}
</script>

<style>
.calculator-container {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.calculator-form {
  margin-bottom: 30rpx;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.label {
  width: 140rpx;
  font-size: 28rpx;
  color: #333;
}

input {
  flex: 1;
  height: 80rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.btn {
  width: 45%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  font-size: 32rpx;
}

.reset {
  background-color: #f5f5f5;
  color: #666;
}

.calculate {
  background-color: #ff6b00;
  color: #fff;
}

.result-area {
  background-color: #f8f8f8;
  border-radius: 16rpx;
  padding: 30rpx;
}

.result-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.result-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.result-item {
  font-size: 28rpx;
  color: #333;
}

.value {
  color: #ffa237;
  font-weight: bold;
}

.price-suggestions {
  margin-top: 30rpx;
}

.suggestion-title {
  font-size: 28rpx;
  color: #dc3545;
  margin-bottom: 20rpx;
}

.suggestions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  font-size: 26rpx;
}

.price {
  color: #ffa237;
}

.calculation-time,
.calculation-note {
  font-size: 24rpx;
  color: #999;
  margin-top: 20rpx;
}

.copy-result {
  margin-top: 30rpx;
  background-color: #ff6b00;
  color: #fff;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
}
</style> 